programming4us
           
 
 
Programming

SOA with .NET and Windows Azure : Service Contracts with WCF (part 1)

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
11/18/2010 11:34:55 AM

WCF Terminology

Before we begin, let’s first establish some WCF terms and associate them with common SOA terms and concepts.

WCF Service Contract

Within WCF, the term “service contract” refers to the technical interface exposed by a WCF service and corresponds to the ServiceContract attribute explained shortly. A service contract is comprised of an interface contract and a service endpoint.

Within regular SOA terminology, the term “service contract” encompasses the entire technical interface in addition to human-readable contract documents, such as SLAs. In this book, the default meaning of the term “service contract” is that of a WCF service contract unless noted otherwise.

SOA Principles & Patterns

A fundamental principle of service-orientation is that services share a formal contract that can express a collection of capabilities in a standardized manner. The Standardized Service Contract principle essentially advocates a “contract first” approach to service development, which requires that we take full control of service contract design and development. Canonical Expression and Canonical Schema fully support this principle by establishing design standards that need to be adhered to by service contracts within a given service inventory boundary. There are some challenges to fully standardizing service contracts in this manner with WCF.


Interface Contract

Within WCF, the term “interface contract” refers to a subset of the service contract comprised of the operation contract, data contract, and message contract (each of which is explained in the upcoming sections). For example, in a WSDL definition, an interface contract corresponds to abstract description.

Operation Contract

The operation contract is the definition of a WCF service operation, method, or capability exposed as part of the interface contract.

Data Contract

Service contracts commonly contain data models to define the structure and typing of message data being exchanged. The de facto means of expressing data models is via the XML Schema Definition Language (XML Schema). Within WCF, XML schemas are referred to as data contracts, especially in relation to service contracts and messages.

Message Contract

As previously mentioned, WCF services interact with each other by the exchange of SOAP messages. Within WCF, the SOAP message design and structure is referred to as the message contract. A message contract can be comprised of definitions for one or more SOAP headers and the SOAP body.

Service Endpoint

The wire-level details required for a service consumer to physically connect to and invoke a service are defined in the service endpoint. Within WCF, the service endpoint is comparable to the concrete description part of a WSDL definition. As explained later, a service endpoint is comprised of address, binding, and contract parts.

The following set of sub-sections explore service contract development with WCF in detail.

The ServiceContract and OperationContract Attributes

A service contract is first created by adding the ServiceContract and OperationContract attributes to a .NET interface:

Example 1.
using System;
using System.ServiceModel;
namespace HelloWorld
{
[ServiceContract]
public interface IGreetings
{
[OperationContract]
string Greet1();
}
}

The ServiceContract attribute indicates that the interface is a service contract for a WCF service and the OperationContract attribute identifies which methods of the interface define service operations.

After the contract has been defined, it is created in a .NET class by implementing the interface, as follows:

Example 2.
class Greetings : IGreetings
{
public string Greet()
{
return "Hello World";
}
}

The name of the interface is IGreetings and the namespace is HelloWorld. The default name and namespace of the contract can be changed by using the name and namespace parameters of the ServiceContract interface:

Example 3.
using System;
using System.ServiceModel;
namespace HelloWorld
{
[ServiceContract
(Namespace=NewNamespace", Name="NewContract")]
public interface IGreetings
{
[OperationContract(Name="GreetRequestor")]
string Greet();
}
}

The internal behavior of a service contract can be changed using behavior attributes. For example, a service can save (persist) its data across sessions using the SessionMode parameter:

Example 4.
namespace HelloWorld
{
[ServiceContract(SessionMode=SessionMode.Required)]
public interface IGreetings
{
[OperationContract(Name="GreetRequestor")]
string Greet();
}
}

A class that implements a service contract is called a service-type. The service-type exchanges data with the service consumer and interaction of the service-type is controlled by the behavior attribute (described shortly).

The service contract must be qualified with a service endpoint in the App.Config or Web.Config file hosted with the contract. The service endpoint contains the address, binding and contract attributes to expose the service to the outside world. As shown in Example 5.5, the address attribute specifies where the service can be found, the binding attribute indicates the service communicates over TCP, and the contract attribute links the service endpoint to the WCF service contract.

SOA Principles & Patterns

The ServiceContract attribute and the OperationContract attribute can be directly applied to the class. In this scenario, the WCF runtime infers the interface from the class. This practice is not recommended, as it runs contrary to the Standardized Service Contract

Example 5.
<endpoint name="EndPoint1"
address="net.tcp://localhost:1234"
binding="netTcpBinding"
contract="IGreetings"
/>

Service endpoints are discussed shortly. First, we need to cover the DataContract and MessageContract attributes.

Data Models and the DataContract Attribute

In WCF, the DataContract attribute is used to generate an XML schema from a CLR type. Members of a data type will not be serialized unless the DataMember attribute is applied, allowing members of the data type to opt-in. The DataContract construct uses XmlFormatter to handle serialization and deserialization of the CLR type, thereby abstracting the complexity involved with generating XML schemas. XmlFormatter is also used to de-serialize the XML schema into a CLR type allowing it to be easily consumed by service consumers.

SOA Principles & Patterns

As mentioned earlier, a primary focal point when applying the Standardized Service Contract  principle is the standardization of the data model exposed by the contract. In fact, this fundamental practice is the basis of Canonical Schema , the pattern that is applied specifically for establishing a consistent and standardized data architecture. The XML Schema Definition Language (XML Schema) has become the de-facto means of defining data models for service contracts that can be shared across platforms. The Validation Abstraction  pattern is further commonly applied to ensure that schema content is balanced and optimized in support of the Service Abstraction principle and to avoid negative consumer-to-contract coupling, as per the Service Loose Coupling  principle.


WCF comes with two XML serializers, namely XmlSerializer and XmlFormatter. XmlFormatter is the successor to XmlSerializer and is the default implementation in WCF. It is used when the DataContract and DataMember attributes are used in a CLR data type. Data contracts are passed between the service and its consumer. The class shown in the following example is a CLR type used to return data from the service:

Example 6.
public class Account
{
public string Account_Number;
public string Account_Name;
public string Type;
public string Cash;
public string Investments;
}

The CLR type can be serialized to an XML schema document by applying the DataContract and DataMember attributes, as shown here:

Example 7.
using System.Runtime.Serialization;
[DataContract(Namespace = "Finance", Name = "AccountContract")]
public class Account
{
[DataMember(Name = "Account_Number")]
public string Account_Number;
[DataMember(Name = "Account_Name")]
public string Account_Name;
[DataMember(Name = "Type", Order = 1)]
public string Type;
[DataMember(Name = "Cash", Order = 1)]
public string Cash;
[DataMember(Name = "Investments", Order = 2)]
public string Investments;
[DataMember(Name = "Total", Order = 2)]
public string Total;
}

The DataContract attribute forces the CLR data type to be serializable in order to be used as a parameter in an operation. One data contract can be a sub-class of another data contract.

XmlFormatter provides less control over how data is serialized to XML. By limiting flexibility, data contracts created using XmlFormatter are optimized for performance and support better versioning. On the other hand, XmlSerializer provides very precise control over how data is represented in XML.

Messaging and the MessageContract Attribute

At its core, WCF uses messages for communication and has a deep commitment to implementing these messages using industry standard protocols, namely SOAP and XML Schema (Figure 1).

Figure 1. Messages pass between the service provider and service consumer.


Messages can be transmitted using industry standard transport protocols, such as HTTP, HTTPS, and TCP, as well as MSMQ and named pipes. Support for sending messages over custom transport protocols is also provided. Both simple and complex message exchange patterns (MEPs) can be expressed, including synchronous and asynchronous interchanges.

Higher level WCF features that layer on top of the messaging framework include extensions for reliability, transactions, queuing, and security features, such as encryption for message confidentiality and digital signing for message integrity.

The message class in the System.ServiceModel namespace can be used to access the contents of a message at the most basic level. By default, these messages are untyped; they conform to the SOAP Envelope construct and can therefore further contain both Body and Header constructs.

SOA Principles & Patterns

Two fundamental patterns that can be realized with the use of SOAP messages are Service Messaging  and Messaging Metadata, the latter of which directly relates to the usage and function of SOAP message headers. The message content structure itself is generally defined using XML Schema, which is often regulated by the application of Canonical Schema  together with the Standardized Service Contract , Service Loose Coupling , and Service Abstraction  principles.


Message contracts are a WCF mechanism used to exercise precise control over the processing of SOAP messages. Whenever a program needs to receive and process message content, it needs to undergo a complete data transformation in order for the underlying service logic to accept it and use it.

The WCF API includes message-related classes that allow you to work at a very granular level. These classes include MessageContract, MessageHeader and MessageBody, all of which are used as attributes to describe the structure of SOAP messages.

In the following code listing, the XML schema produced by the MsgHeader data contract will appear in the SOAP header block. The MsgBody data contract will appear in the SOAP body.

Example 8.
  [DataContract]
public class MsgHeader {
[DataMember]
public string loginName;
[DataMember]
public string password;
}
[DataContract]
public class MsgBody
{
[DataMember(Order=1)]
public string name;
[DataMember(Order=2)]
public int phone;
[DataMember(Order=3)]
public int email;
}
[MessageContract]
public class ContactMessage {
[MessageHeader]
public MsgHeader msgHeader;
[MessageBody]
public MsgBody msgBody;
}


To use the MessageContract developed in Example 5.8, the parameter of the operation needs to be changed, as shown here:

Example 9.
 [ServiceContract]
public interface IContactService
{
[OperationContract]
public void InsertContact(ContactMessage contactMessage);
}

Prior to using the message contract, the SOAP message on the wire would exist as follows:

Example 10.
<S:Envelope>
<S:Header>
</S:Header>
<S:Body>
</S:Body>
</S:Envelope>

The InsertContact operation would now create the following SOAP message:

Example 11.
<S:Envelope>
<S:Header>
<S:loginName>user</S:loginName>
<S:password>password</S:password>
</S:Header>
<S:Body>
<S:name> ... </S:name>
<S:phone> ... </S:phone>
<S:email> ... </S:email>
</S:Body>
</S:Envelope>

Note

.NET version 3.5 SP1 expanded the reach of the data contract serializer by relaxing the need of having [DataContract]/[DataMember] on types and by supporting an interoperable mechanism for dealing with object references.


Service Endpoints and the endpoint Element

The information required for a service consumer to invoke a given service is expressed with the endpoint element, which effectively establishes what is called a service endpoint.

Specifically, a service endpoint contains the following parts:

  • address – the location of the service

  • binding – service invocation requirements (including information about security and reliability policies)

  • contract – a reference to the service contract that the service endpoint applies to

Service endpoints (Figure 4) abstract the underlying service logic and implementation. You are further able to choose which service operations from the service contract to explicitly or implicitly expose.

Figure 4. A service consumer communicates with the service using information provided by the endpoint.


The endpoint construct can be configured in the Web.Config file or the App.Config file, as shown here:

Example 12.
<system.serviceModel>
<services>
<service name="AccountService">
<endpoint name="EndPoint1"
address="net.tcp://localhost:1234"
binding="netTcpBinding"
contract="IAccount" />
</service>
</services>
</system.serviceModel>

A single service can have more than one service endpoint. In the next example, the IAccount contract can be accessed on port 1234 using TCP, as well as port 8000 using HTTP:

Example 13.
<system.serviceModel>
<services>
<service name="AccountService">
<endpoint name="EndPoint1"
address="net.tcp://localhost:1234"
binding="netTcpBinding"
contract="IAccount" />
<endpoint name="EndPoint3"
address="http://localhost:8000"
binding="basicHttpBinding"
contract="IAccount" />
</service>
</services>
</system.serviceModel>

Note

The service endpoint, as expressed via the endpoint element, is further represented by the ServiceEndpoint class in WCF and is collectively comprised of an EndpointAddress class, a Binding class, and a ContractDescription class corresponding to the endpoint’s address, binding, and contract.


Address

Location transparency is achieved using the endpoint address, which specifies where the service can be found, as well as the transport protocol used to communicate with it. The address attribute is assigned a Uniform Resource Identifier (URI), as follows:

Example 14.
[transport]://[domain or machine]:[optional port]
net.tcp://localhost:1234

URIs in a Nutshell

URIs are short strings used to identify a resource over a network or the Web. For example, “http://www.example.org:322/accounts.svc/secureEndpoint” is a valid URI.

This URI has four parts:

  • transport – specifies the transport protocol used to reach the resource (for example, “http”, “ftp”, “mailto”, “urn”, “mms”, etc.)

  • location – the location of the server (for example, “www.example.org”)

  • port – port where the resource is available (for example, “322”)

  • path – the exact location of the resource (for example, “/accounts.svc/secureEndpoint”)

The sample URI we just introduced can be interpreted as follows: “The resource is located on the server www.example.org and can be reached using the HTTP protocol. It can be accessed on port 322 and the path to it is “/accounts.svc/secureEndpoint.”


The endpoint address is represented in WCF by the EndpointAddress class, which includes a URI, an identity, and a collection of optional headers (Figure 2).

Figure 2. The parts of the EndpointAddress class in WCF.


The primary purpose of this class is to represent the URI. It also contains properties that include an identity and a collection of optional headers. These headers are used to provide additional, more detailed information. For example, they may indicate which instance of a service should be used to process an incoming message from a particular consumer.

The endpoint address can be specified imperatively in the code or declaratively through configuration. Defining the endpoint address in configuration is preferred, as the address and binding values used for development will (hopefully) be different from the corresponding values used for when the service is deployed in a production environment. Keeping the address and binding in the configuration file allows them to change without requiring recompilation and redeployment of the service.

Other -----------------
- Cloud Security and Privacy : Data Security and Storage
- iPad SDK : Working with Documents - Desktop Synchronization
- Required Project Images for iPad Apps
- iPhone SDK : GameKit Voice Chat
- iPhone SDK : Creating Basic GameKit Services (part 2) : Sending and Receiving Data
- iPhone SDK : Creating Basic GameKit Services (part 1)
- iPad : Navigating with Maps
- Adding iPad to the Mix
- A Brief History of Legacy .NET Distributed Technologies : .NET Remoting
- A Brief History of Legacy .NET Distributed Technologies : .NET Enterprise Services
- iPad SDK : Outputting to an External Screen
- iPad SDK : Displaying Multiple Videos
- Parallel Programming Drivers
- Parallel Programming with Microsoft .Net : Parallel Loops - An Example
- Parallel Programming with Microsoft .Net : Parallel Loops - The Basics
- What is New in iPhone SDK 3.2 for the iPad (part 2)
- What is New in iPhone SDK 3.2 for the iPad (part 1)
- Programming with DirectX : Rendering Geometry - Colors
- ASP.NET Security : The Membership and Role Management API (part 3) - Role
- ASP.NET Security : The Membership and Role Management API (part 2) - Provider
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
programming4us programming4us